/*
 * InterfaceGenerator.java
 *
 * Created on 08-Jul-2009, 13:35:22
 * Copyright newtonr6
 */
package portalTaverna;

import javax.faces.FacesException;
import com.icesoft.faces.component.ext.HtmlDataTable;
import com.icesoft.faces.component.ext.HtmlInputText;
import com.icesoft.faces.component.ext.HtmlOutputText;
import com.icesoft.faces.component.ext.HtmlInputTextarea;
import com.icesoft.faces.component.ext.HtmlSelectBooleanCheckbox;
import com.icesoft.faces.component.ext.HtmlSelectOneMenu;
import com.icesoft.faces.component.ext.HtmlSelectOneRadio;
import java.io.*;
import java.util.Iterator;
import java.util.Vector;
import javax.faces.event.ValueChangeEvent;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 */
public class InterfaceGenerator {

    Vector inputsVector;
    Vector valuesVector;
    int addedCount;
    int selectedInputIndex;
    String desc = "";
    int count;
    int noOfInputs;
    private inputModel[] inputs;
    private SessionBean sb = new SessionBean();
    String serverID;
    String workflow;
    String thumb = "/resources/css-images/connect_idle.gif";
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">
    private int __placeholder;

    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    private HtmlDataTable inputsTable = new HtmlDataTable();

    public HtmlDataTable getInputsTable() {
        return inputsTable;
    }

    public void setInputsTable(HtmlDataTable hdt) {
        this.inputsTable = hdt;
    }

    private HtmlOutputText wfName = new HtmlOutputText();

    public HtmlOutputText getWfName(){
        return wfName;
    }

    public void setWfName(HtmlOutputText hot){
        this.wfName = hot;
    }
    private String selectedInput = null;

    public String getSelectedInput() {
        return selectedInput;
    }

    public void setSelectedInput(String str) {
        this.selectedInput = str;
    }
    private HtmlInputText nameTextarea = new HtmlInputText();

    public HtmlInputText getNameTextarea() {
        return nameTextarea;
    }

    public void setNameTextarea(HtmlInputText ita) {
        this.nameTextarea = ita;
    }
    private String savedMessage = "Description not saved";

    public String getSavedMessage() {
        return savedMessage;
    }

    public void setSavedMessage(String str) {
        savedMessage = str;
    }
    private String savedMessageStyle = "color:red; font-weight:bold";

    public String getSavedMessageStyle() {
        return savedMessageStyle;
    }

    public void setSavedMessageStyle(String str) {
        savedMessageStyle = str;
    }
    private HtmlInputText optionInputText = new HtmlInputText();

    public HtmlInputText getOptionInputText() {
        return optionInputText;
    }

    public void setOptionInputText(HtmlInputText it) {
        this.optionInputText = it;
    }
    private HtmlInputTextarea exampleTextarea = new HtmlInputTextarea();

    public HtmlInputTextarea getExampleTextarea() {
        return exampleTextarea;
    }

    public void setExampleTextarea(HtmlInputTextarea ita) {
        this.exampleTextarea = ita;
    }
    private HtmlInputTextarea descriptionTextarea = new HtmlInputTextarea();

    public HtmlInputTextarea getDescriptionTextarea() {
        return descriptionTextarea;
    }

    public void setDescriptionTextarea(HtmlInputTextarea ita) {
        this.descriptionTextarea = ita;
    }
    private HtmlSelectOneMenu uicMenu = new HtmlSelectOneMenu();

    public HtmlSelectOneMenu getuicMenu() {
        return uicMenu;
    }

    public void setuicMenu(HtmlSelectOneMenu sol) {
        this.uicMenu = sol;
    }
    private String addedOption = new String();

    public String getAddedOption() {
        return addedOption;
    }

    public void setAddedOption(String str) {
        this.addedOption = str;
    }
    private HtmlSelectOneMenu dataTypesMenu = new HtmlSelectOneMenu();

    public HtmlSelectOneMenu getDataTypesMenuMenu() {
        return dataTypesMenu;
    }

    public void setDataTypesMenuMenu(HtmlSelectOneMenu sol) {
        this.dataTypesMenu = sol;
    }
    private HtmlOutputText submitStatusText = new HtmlOutputText();

    public HtmlOutputText getSubmitStatusText() {
        return submitStatusText;
    }

    public void setSubmitStatusText(HtmlOutputText hot) {
        this.submitStatusText = hot;
    }
    private HtmlInputText minInputText = new HtmlInputText();

    public HtmlInputText getMinInputText() {
        return minInputText;
    }

    public void setMinInputText(HtmlInputText it) {
        this.minInputText = it;
    }
    private HtmlInputText maxInputText = new HtmlInputText();

    public HtmlInputText getMaxInputText() {
        return maxInputText;
    }

    public void setMaxInputText(HtmlInputText it) {
        this.maxInputText = it;
    }
    private HtmlInputText lengthInputText = new HtmlInputText();

    public HtmlInputText getLengthInputText() {
        return lengthInputText;
    }

    public void setLengthInputText(HtmlInputText it) {
        this.lengthInputText = it;
    }
    private HtmlSelectOneRadio typeRadio = new HtmlSelectOneRadio();

    public HtmlSelectOneRadio getTypeRadio() {
        return typeRadio;
    }

    public void setTypeRadio(HtmlSelectOneRadio sor) {
        this.typeRadio = sor;
    }
    private boolean editNameVis = false;

    public boolean getEditNameVis() {
        return editNameVis;
    }

    public void setEditNameVis(boolean rv) {
        this.editNameVis = rv;
    }
    private boolean editName1Vis = false;

    public boolean getEditName1Vis() {
        return editName1Vis;
    }

    public void setEditName1Vis(boolean rv) {
        this.editName1Vis = rv;
    }
    private boolean compsVis = false;

    public boolean getcompsVis() {
        return compsVis;
    }

    public void setcompsVis(boolean cv) {
        this.compsVis = cv;
    }
    private boolean popupVis = false;

    public boolean getPopupVis() {
        return popupVis;
    }

    public void setPopupVis(boolean pv) {
        this.popupVis = pv;
    }
    private boolean confirmVis = false;

    public boolean getConfirmVis() {
        return confirmVis;
    }

    public void setConfirmVis(boolean cv) {
        confirmVis = cv;
    }
    private boolean listInputVis = false;

    public boolean getListInputVis() {
        return listInputVis;
    }

    public void setListInputVis(boolean cv) {
        listInputVis = cv;
    }
    private boolean descVis = false;

    public boolean getDescVis() {
        return descVis;
    }

    public void setDescVis(boolean cv) {
        descVis = cv;
    }
    private boolean restrictVis = false;

    public boolean getRestrictVis() {
        return restrictVis;
    }

    public void setRestrictVis(boolean rv) {
        this.restrictVis = rv;
    }
    private boolean stringVis = true;

    public boolean getStringVis() {
        return stringVis;
    }

    public void setStringVis(boolean rv) {
        this.stringVis = rv;
    }

    // </editor-fold>
    /**
     * <p>Construct a new Page bean instance.</p>
     */

    public SessionBean getSB() {
        return sb;
    }

    public void setSB(SessionBean sessb) {
        this.sb = sessb;
    }

    public InterfaceGenerator() {
    }

    public String showPorts() {


        thumb = "/resources/css-images/connect_idle.gif";
        count = 0;
        sb.setDescription("");

        WorkflowDetails selectedWorkflow = ServerWorkflows.workflows[ServerWorkflows.workflowsTable.getRowIndex()];
        String WfId = selectedWorkflow.id;
        sb.setWorkflowName("Server workflow ID: " + WfId);
        sb.setServerID(WfId);

        try {
            DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
            Factory.setNamespaceAware(false);
            DocumentBuilder builder = Factory.newDocumentBuilder();
            Document doc = builder.parse("http://rpc212.cs.man.ac.uk:8081/taverna-server-0.2.1/rest/workflows/" + WfId);
            //creating an XPathFactory:
            XPathFactory factory = XPathFactory.newInstance();
            //using this factory to create an XPath object:
            XPath xpath = factory.newXPath();
            //XPath object created compiles the XPath expression for inputs:
            XPathExpression workflowXmlExpr = xpath.compile("//xml/text()");
            Object workflowXmlResult = workflowXmlExpr.evaluate(doc, XPathConstants.NODESET);
            NodeList workflowXmlNodeList = (NodeList) workflowXmlResult;

            //System.out.println(workflowXmlNodeList.item(0).getNodeValue());

            //get input names
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(workflowXmlNodeList.item(0).getNodeValue()));

            Document wfXml = builder.parse(is);

            XPathExpression inputsExpr = xpath.compile("//dataflow[1]/inputPorts/port/name/text()");
            Object inputsResult = inputsExpr.evaluate(wfXml, XPathConstants.NODESET);
            NodeList inputsNodeList = (NodeList) inputsResult;

            System.out.println(inputsNodeList.item(0).getNodeValue());


            //set workflow variable values from xpath expressions
            //desc = descNodeList.item(0).getNodeValue();

            if (!inputsNodeList.equals(null)) {
                inputs = new inputModel[inputsNodeList.getLength()];
                for (int i = 0; i < inputsNodeList.getLength(); i++) {
                    inputModel inputName = new inputModel(inputsNodeList.item(i).getNodeValue(), null, null, null, null, null, null, null, null,
                            "Interface component not defined", "/resources/icons/png/16x16/Warning.png", false);

                    inputs[i] = inputName;
                }
            } else {
                inputs = new inputModel[1];
                inputModel in = new inputModel("no inputs", null, null, null, null, null, null, null, null,
                        "Interface component not defined", "/resources/icons/png/16x16/Warning.png", false);
                inputs[0] = in;
            }

        //thumb = thumbNodeList.item(0).getNodeValue();

        } catch (Exception e) {
        }

        inputsTable.setValue(inputs);
        wfName.setValue("Server workflow ID: " + WfId);
        sb.setInputModelArr(inputs);
        noOfInputs = inputs.length;
        //InterfaceGenerator.setConfirmVis(true);
        submitStatusText.setValue("");
        inputsVector = new Vector();
        //test = workflowDetails.getInputs()[0];
        //workflow = Page1.workflowsTable.getRowIndex();
        //thumb = workflowDetails.getThumb();
        return "server";
    }

    public String editName() {
        inputsTable.setValue(sb.getInputModelArr());
        inputModel[] im = sb.getInputModelArr();
        inputModel o = im[0];
        System.out.println(sb.getWorkflowName());
        editNameVis = false;
        editName1Vis = true;
        return null;
    }

    public String confirmEditName() {
        try {
            String newName = (String) nameTextarea.getText();
            System.out.println(newName);
            wfName.setValue(newName);
            sb.setWorkflowName(newName);
            editNameVis = true;
        } catch (Exception e) {
            System.out.println(e);
        }
        return null;
    }

    public String toggleDesc() {
        savedMessage = "Description not saved";
        savedMessageStyle = "color:red; font-weight:bold";
        descVis = !descVis;
        return null;
    }

    public String addComponent() {

        valuesVector = new Vector();

        popupVis = true;
        selectedInputIndex = inputsTable.getRowIndex();
        inputModel[] imArr = sb.getInputModelArr();
        selectedInput = imArr[selectedInputIndex].name;

        exampleTextarea.setValue("example input");
        descriptionTextarea.setValue("input description");

        return null;
    }

    public String cancelAddComponent() {
        valuesVector.clear();
        popupVis = false;
        return null;
    }

    public String addOption() {

        valuesVector.add(optionInputText.getValue());
        addedOption = (String) optionInputText.getValue() + " added to list";
        optionInputText.setValue("");
        return null;
    }

    public String confirmAddComponent() {

        inputModel[] inputsArr = sb.getInputModelArr();
        inputModel input = inputsArr[selectedInputIndex];

        String name = input.name;
        String UIComponent = (String) uicMenu.getValue();
        String dataType = (String) dataTypesMenu.getValue();
        String min = (String) minInputText.getValue();
        String max = (String) maxInputText.getValue();
        String length = (String) lengthInputText.getValue();
        String example = (String) exampleTextarea.getValue();
        String description = (String) descriptionTextarea.getValue();

        inputModel inputOut = new inputModel(name, UIComponent, valuesVector, dataType, min, max, length, example, description, "", "", true);

        inputsVector.add(inputOut);

        count = count + 1;
        if (count == inputsArr.length) {
            confirmVis = true;
        }

        /*System.out.println(name + ", " + UIComponent + ", " + dataType + ", " + example);
        Iterator itre = valuesVector.iterator();
        while (itre.hasNext()) {
        System.out.println((String) itre.next());
        }*/

        Iterator itrb = inputsVector.iterator();
        while (itrb.hasNext()) {
            inputModel im = (inputModel) (itrb.next());
            System.out.println(im.name);
            Iterator itrc = im.options.iterator();
            while (itrc.hasNext()) {
                System.out.println((String) itrc.next());
            }
        }

        input.message = "Component defined";
        input.icon = "/resources/icons/png/16x16/Yes.png";
        input.complete = true;

        exampleTextarea.setValue("example input");
        descriptionTextarea.setValue("input description");
        optionInputText.setValue("");
        addedOption = "";
        popupVis = false;

        return null;
    }

    public String writeXML() {

        inputModel[] inputsArr = sb.getInputModelArr();
        inputModel input = inputsArr[selectedInputIndex];

        String description = sb.getDescription();
        if (description.equals("")) {
            description = "No description available";
        }
        String tmpDesc = description.replaceAll("<", "&lt;");
        String tmpDesc2 = tmpDesc.replaceAll(">", "&gt;");
        description = tmpDesc2;

        //description.replace(">", "&gt;");

        try {
            // Create file
            boolean exists = (new File("wf_data/" + sb.getWorkflowName() + ".xml")).exists();
            if (exists != true) {
                File file = new File("wf_data/" + sb.getWorkflowName() + ".xml");
                System.out.print("exists");

                FileWriter fstream = new FileWriter(file, true);
                BufferedWriter out = new BufferedWriter(fstream);

                out.write("<workflow>\n");
                out.write("\t<idonserver>" + sb.getServerID() + "</idonserver>\n");
                out.write("\t<description>" + description + "</description>\n");
                out.write("\t<inputs>\n");
                Iterator itrb = inputsVector.iterator();
                while (itrb.hasNext()) {

                    inputModel im = (inputModel) (itrb.next());

                    out.write("\t\t<input>\n\t\t\t" +
                            "<name>" + im.name + "</name>\n\t\t\t" +
                            "<type>" + im.UIComponent + "</type>\n\t\t\t" +
                            "<values>");

                    Iterator itr = im.options.iterator();
                    while (itr.hasNext()) {
                        out.write("\n\t\t\t\t<value>" + (String) itr.next() + "</value>");
                    }



                    if (im.example.equals("")) {
                        im.example = "no example input given";
                    }

                    if (im.description.equals("")) {
                        im.description = "no description given";
                    }


                    out.write("\n\t\t\t</values>\n\t\t\t" +
                            /*"<restriction>\n\t\t\t\t"+
                            "<min>"+im.min+"</min>\n\t\t\t\t" +
                            "<max>"+im.max+"</max>\n\t\t\t\t" +
                            "<length>"+im.length+"</length>\n\t\t\t" +
                            "</restriction>\n\t\t\t" +*/
                            "<example>" + im.example + "</example>\n\t\t\t" +
                            "<description>" + im.description + "</description>\n\t\t" +
                            "</input>\n");
                }

                out.write("\t</inputs>\n");
                out.write("</workflow>");

                out.close();

                confirmVis = false;

                submitStatusText.setStyle("color:green; font-size:12px; font-weight:bold");
                submitStatusText.setValue("Interface schema saved");
            } else {
                submitStatusText.setStyle("color:red; font-size:12px; font-weight:bold");
                submitStatusText.setValue("An interface schema for a workflow with this name has already been defined");
            }

        } catch (Exception ex) {//Catch exception if any
            System.out.println("Error: " + ex.getMessage());
        }


        return null;
    }

    public void componentChanged(ValueChangeEvent event) {

        String UIComponent = (String) uicMenu.getValue();
        if (UIComponent.equals("dropdown") || UIComponent.equals("checkbox") || UIComponent.equals("radio")) {
            listInputVis = true;
        } else {
            listInputVis = false;
        }
    }

    public void restrictionChanged(ValueChangeEvent vce) {

        restrictVis = !restrictVis;
    }

    public void typeChanged(ValueChangeEvent event) {

        String dataType = (String) typeRadio.getValue();
        if (dataType.equals("String")) {
            stringVis = true;
        } else {
            stringVis = false;
        }
    }

    public void saveDescription(ValueChangeEvent event) {

        savedMessage = "Description saved";
        savedMessageStyle = "color:green; font-weight:bold";
    }
}

